/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.ext.echarts.builder.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;

public class DefaultSingleValueCategoryModel extends AbstractEChartsModel implements SingleValueCategoryModel{

    private static final long serialVersionUID = 20140319154808L;
    private List<Comparable<?>> _categoryList = new ArrayList<Comparable<?>>();
    private Map<Comparable<?>, Number> _categoryMap = new HashMap<Comparable<?>, Number>();

    //-- SingleValueCategoryModel --//
    public Comparable<?> getCategory(int index) {
        return _categoryList.get(index);
    }

    public Collection<Comparable<?>> getCategories() {
        return _categoryList;
    }

    public Number getValue(Comparable<?> category) {
        return _categoryMap.get(category);
    }

    public void setValue(Comparable<?> category, Number value) {
        if (!_categoryMap.containsKey(category)) {
            final int cIndex = _categoryList.size();
            _categoryList.add(category);
            _categoryMap.put(category, value);
            fireEvent(EChartsDataEvent.ADDED, null, category, 0, cIndex, value);
        } else {
            Number ovalue = _categoryMap.get(category);
            if (Objects.equals(ovalue, value)) {
                return;
            }
            final int cIndex = _categoryList.indexOf(category);
            _categoryMap.put(category, value);
            fireEvent(EChartsDataEvent.CHANGED, null, category, 0, cIndex, value);
        }
    }

    public void removeValue(Comparable<?> category) {
        _categoryMap.remove(category);

        final int cIndex = _categoryList.indexOf(category);

        Comparable<?> value = _categoryList.remove(category);
        fireEvent(EChartsDataEvent.REMOVED, null, category, 0, cIndex, value);
    }

    public void clear() {
        _categoryMap.clear();
        _categoryList.clear();
        fireEvent(EChartsDataEvent.REMOVED, null, null, -1, -1, null);
    }


    public Object clone() {
        DefaultSingleValueCategoryModel clone = (DefaultSingleValueCategoryModel) super.clone();
        if (_categoryList != null)
            clone._categoryList = new ArrayList<Comparable<?>>(_categoryList);
        if (_categoryMap != null)
            clone._categoryMap = new HashMap<Comparable<?>, Number>(_categoryMap);
        return clone;
    }

}
